package cn.wit.summit.chwan.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GameDailyNewAdapter;
import cn.wit.summit.chwan.adapters.GameStarterAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.request.DailyNewRequest;
import cn.wit.summit.chwan.models.response.GameStarterIndexResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemGridDownloadView;
import cn.wit.summit.chwan.widgets.ItemListPartView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * 游戏首发
 * Created by Alan on 2018/4/17.
 */

public class GameStarterActivity extends BaseActivity {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.titleRightTv)
    TextView titleRightTv;
    @Bind(R.id.topTitleLl)
    LinearLayout topTitleLl;

    private int pn = 1;
    private int pc = 20;
    private GameStarterAdapter mGameStarterAdapter;

    private List<GameStarterAdapter.ViewBean> viewBeans = new ArrayList<>();
    private LinearLayoutManager layoutManager;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private int fisrtTitlePo = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_starter);
        ButterKnife.bind(this);

        setBarTitleTx(getResources().getString(R.string.recommend_daily_2_tx));
        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        initList();
    }

    @Override
    public void reGetData() {
        super.reGetData();
        viewBeans.clear();
        mGameStarterAdapter.notifyDataSetChanged();
        pn = 1;
        ketTime = "";
        getGameStarterData();
        refreshLayout.autoRefresh();
    }

    private void initList() {
        topTitleLl.setVisibility(View.GONE);

        mGameStarterAdapter = new GameStarterAdapter(this, viewBeans);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mGameStarterAdapter);
        recyclerView.setFocusable(false);
//        recyclerView.addOnScrollListener(new MyScrollListener());
        refreshLayout.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                ketTime = "";
                getGameStarterData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getGameStarterData();
            }
        });

        //触发自动刷新
//        refreshLayout.autoRefresh();
        showSkeleton();
        pn = 1;
        ketTime = "";
        getGameStarterData();

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (null != layoutManager) {
                    //当前条目索引
                    int position = layoutManager.findFirstVisibleItemPosition();
                    int position2 = layoutManager.findLastVisibleItemPosition();
                    if (fisrtTitlePo==-1) {
                        for (int i=0;i<position2;i++) {
                            int viewType = mGameStarterAdapter.getItemViewType(position);
                            if (viewType == GameDailyNewAdapter.ViewType.TYPE_TITLE.ordinal()) {
                                fisrtTitlePo = position;
                                break;
                            }
                        }
                    }
                    if (position > fisrtTitlePo) {
                        topTitleLl.setVisibility(View.VISIBLE);
                    } else {
                        topTitleLl.setVisibility(View.GONE);
                    }

                    int viewType = mGameStarterAdapter.getItemViewType(position);
                    if (viewType == GameStarterAdapter.ViewType.TYPE_TITLE.ordinal()) {
                        GameStarterAdapter.ViewBean viewBean = viewBeans.get(position);
                        GameStarterAdapter.ViewBean.TitleBean temp = (GameStarterAdapter.ViewBean.TitleBean) viewBean.getObj();
                        titleRightTv.setText(temp.time);
                    }
                }
            }
        });
    }

    private void getGameStarterData() {
        DailyNewRequest tempRequest = retrofitManager.getGameNewRequest(pn, pc);
        api.getGameNew(tempRequest).enqueue(new MyCallback<ResponseBase<List<GameStarterIndexResponse>>>() {
            @Override
            public void onSuccess(ResponseBase<List<GameStarterIndexResponse>> model) {
                hideSkeleton();
                updataUi(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                if (code == -4) {
                    if (pn == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    }
                } else {
                    refreshLayout.finishLoadMore(false);
                    refreshLayout.finishRefresh();
                    hideSkeleton();
                    showToast(msg);
                }
            }
        });
    }

    private String ketTime = "";
//    List<GameStarterIndexResponse> gridTemp = new ArrayList<>();
//    private boolean isEnd = true;
//    private int notEndPo;

    private void updataUi(List<GameStarterIndexResponse> data) {

        if (data == null) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        if (pn == 1) {
            mGameStarterAdapter.clearTempData();
            viewBeans.clear();
        }

        for (int i = 0; i < data.size(); i++) {
            GameStarterIndexResponse temp = data.get(i);

            if (ketTime.equals("")) {
                ketTime = temp.getGame_f_times();

                GameStarterAdapter.ViewBean.TitleBean titleBean = new GameStarterAdapter.ViewBean.TitleBean(temp.getGame_f_times());
                GameStarterAdapter.ViewBean viewBean = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_TITLE, titleBean);
                titleRightTv.setText(titleBean.time);
                viewBeans.add(viewBean);
            }

            if (!ketTime.equals(temp.getGame_f_times())) {
                ketTime = temp.getGame_f_times();

                GameStarterAdapter.ViewBean lineBean = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_LINE, null);
                viewBeans.add(lineBean);

                GameStarterAdapter.ViewBean.TitleBean titleBean = new GameStarterAdapter.ViewBean.TitleBean(temp.getGame_f_times());
                GameStarterAdapter.ViewBean viewBean = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_TITLE, titleBean);
                viewBeans.add(viewBean);
            }

            GameStarterAdapter.ViewBean viewImg = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_IMAGE, temp);
            viewBeans.add(viewImg);
            GameStarterAdapter.ViewBean viewList = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_LIST, temp);
            viewBeans.add(viewList);

            GameStarterAdapter.ViewBean lineSmallBean = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_LINE_SMALL, null);
            viewBeans.add(lineSmallBean);

        }

        if (data.size() <= 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
        } else {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            pn++;
        }
        mGameStarterAdapter.notifyDataSetChanged();
    }

//    private void updataUi(List<GameStarterIndexResponse> data) {
//
//        if (data == null) return;
//
//        if (pn == 1)
//            viewBeans.clear();
//
//        for (int i = 0; i < data.size(); i++) {
//            GameStarterIndexResponse temp = data.get(i);
//
//            if (ketTime.equals("")) {
//                ketTime = temp.getGame_f_times();
//                GameStarterAdapter.ViewBean.TitleBean titleBean = new GameStarterAdapter.ViewBean.TitleBean(temp.getGame_f_times());
//                GameStarterAdapter.ViewBean viewBean = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_TITLE, titleBean);
//                viewBeans.add(viewBean);
//            }
//
//            if (ketTime.equals(temp.getGame_f_times())) {
//                if (isEnd) {
//                    gridTemp.add(temp);
//                    if (gridTemp.size() == 3 || i == (data.size() - 1)) {
//                        List<GameStarterIndexResponse> add = new ArrayList<>();
//                        add.addAll(gridTemp);
//                        GameStarterAdapter.ViewBean view = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_GRID, add);
//                        viewBeans.add(view);
//                        gridTemp.clear();
//                    }
//                } else {
//                    isEnd = mGameStarterAdapter.setItemDataByPo(notEndPo, temp);
//                }
//                //处理上一页没有占满，下一页又有同一天的数据的情况
//                if (gridTemp.size() != 3 && i == (data.size() - 1)) {
//                    isEnd = false;
//                    notEndPo = mGameStarterAdapter.getItemCount()-1;
//                } else {
//                    isEnd = true;
//                }
//            } else {
//                if (gridTemp.size() > 0) {
//                    List<GameStarterIndexResponse> add = new ArrayList<>();
//                    add.addAll(gridTemp);
//                    GameStarterAdapter.ViewBean view = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_GRID, add);
//                    viewBeans.add(view);
//                    gridTemp.clear();
//                }
//
//                gridTemp.add(temp);
//                ketTime = temp.getGame_f_times();
//                GameStarterAdapter.ViewBean lineBean = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_LINE, null);
//                viewBeans.add(lineBean);
//                GameStarterAdapter.ViewBean.TitleBean titleBean = new GameStarterAdapter.ViewBean.TitleBean(temp.getGame_f_times());
//                GameStarterAdapter.ViewBean viewBean = new GameStarterAdapter.ViewBean(GameStarterAdapter.ViewType.TYPE_TITLE, titleBean);
//                viewBeans.add(viewBean);
//            }
//        }
//
//        mGameStarterAdapter.notifyDataSetChanged();
//        if (pn == 1) {
//            refreshLayout.finishRefresh();
//            refreshLayout.setNoMoreData(false);
//        } else {
//            if (data.size() <= 0) {
//                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
//            } else {
//                refreshLayout.finishLoadMore();
//            }
//        }
//        pn++;
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = mGameStarterAdapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            if (str.contains("|")) {
                String[] sl = str.split("\\|");
                GameListBaseBean bean = mGameStarterAdapter.getBeanData(Integer.valueOf(sl[0]), Integer.valueOf(sl[1]));
                if (bean == null) return;
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                    table.setDownprogress(downloadEvent.getProgress());
                }
                View view = layoutManager.findViewByPosition(Integer.valueOf(sl[0]));
                if (view == null) {
                    return;
                }

                ItemGridDownloadView itemView = null;
                switch (Integer.valueOf(sl[1])) {
                    case 0:
                        itemView = view.findViewById(R.id.itemGridDownloadViewOne);
                        break;
                    case 1:
                        itemView = view.findViewById(R.id.itemGridDownloadViewTwo);
                        break;
                    case 2:
                        itemView = view.findViewById(R.id.itemGridDownloadViewThree);
                        break;
                }

                if (itemView == null) {
                    return;
                }
                DownloadViewStroke dowView = itemView.getDownView();
                dowView.updateButn(table);
            } else {
                GameListBaseBean bean = mGameStarterAdapter.getBeanData(Integer.valueOf(str), 0);
                if (bean == null) return;
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                    table.setDownprogress(downloadEvent.getProgress());
                }

                View view = layoutManager.findViewByPosition(Integer.valueOf(str));
                ItemListPartView itemView = view.findViewById(R.id.itemListPartView);
                if (itemView == null) {
                    return;
                }
                DownloadViewStroke dowView = itemView.getDownView();
                dowView.updateButn(table);
            }
        }
        super.onEventMainThread(downloadEvent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (viewBeans != null && viewBeans.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_game_starter_skeleton;
    }
}
